//You are given an array prices where prices[i] is the price of a given stock on
// the ith day. 
//
// You want to maximize your profit by choosing a single day to buy one stock an
//d choosing a different day in the future to sell that stock. 
//
// Return the maximum profit you can achieve from this transaction. If you canno
//t achieve any profit, return 0. 
//
// 
// Example 1: 
//
// 
//Input: prices = [7,1,5,3,6,4]
//Output: 5
//Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 
//6-1 = 5.
//Note that buying on day 2 and selling on day 1 is not allowed because you must
// buy before you sell.
// 
//
// Example 2: 
//
// 
//Input: prices = [7,6,4,3,1]
//Output: 0
//Explanation: In this case, no transactions are done and the max profit = 0.
// 
//
// 
// Constraints: 
//
// 
// 1 <= prices.length <= 105 
// 0 <= prices[i] <= 104 
// 
// Related Topics 数组 动态规划 
// 👍 1615 👎 0


package leetcode.editor.cn;

//Java：Best Time to Buy and Sell Stock
class P121BestTimeToBuyAndSellStock {
    public static void main(String[] args) {
        Solution solution = new P121BestTimeToBuyAndSellStock().new Solution();
        // TO TEST
        System.out.println(solution.maxProfit(new int[]{7, 1, 5, 3, 6, 4}));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int maxProfit(int[] prices) {
            //1:当前状况，money，1.买入money-price,2.卖出mongey+price,2.啥都不做money
            int[][] profit = new int[prices.length][2];
            //1.当前持有股票，1.昨天买的，今天没动，2.今天买的
            //2.没持有股票，2.昨天就没有，今天没买，2.今天卖了
            //1.第一天，profit[0][1]=-Inifinite
            profit[0][1] = -prices[0];
            profit[0][0] = 0;
            int max = 0;
            for (int i = 1; i < prices.length; i++) {
                int price = prices[i];
                profit[i][0] = Math.max(profit[i - 1][0], price + profit[i - 1][1]);
                profit[i][1] = Math.max(profit[i - 1][1],  - price);

            }
            return profit[profit.length - 1][0];
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}